import { createRouter, createWebHashHistory } from 'vue-router'
import store from '../store/index.js'
import otherRoutes from './routes/other.js'
import permissionRoutes from './routes/permission.js'
import EventCenter from '/src/_util/publish-subscribe.js'
import NProgress from '/src/_util/nprogress.js'

const router = createRouter({
    history: createWebHashHistory('/zs-vue3-element-admin/'),
    routes: [
		...otherRoutes,
        {
            path: '/main',
            name: 'main',
            redirect: '/main/home',
            component: () => import(/* webpackChunkName: "main" */ '../views/Index.vue'),
            children: [],
        }
    ]
})

// 处理菜单
const handleMenus = function (asideMenus, permissionRoutes) {
	let routes = [];
	(function handle (asideMenus, permissionRoutes) {
		let findRes = null
		for (let i = 0; i < asideMenus.length; i++) {
			findRes = permissionRoutes.find(item => item.id == asideMenus[i].id)
			if (findRes) {
				asideMenus[i].id = findRes.id
				asideMenus[i].path = findRes.path
				asideMenus[i].name = findRes.name
				asideMenus[i].redirect = findRes.redirect
				asideMenus[i].component = findRes.component
				// asideMenus[i].meta['title'] = findRes.meta.title
				asideMenus[i].meta['iconName'] = findRes.meta.iconName
				asideMenus[i].meta['permission'] = findRes.meta.permission
				asideMenus[i].meta['keepAlive'] = findRes.meta.keepAlive
				asideMenus[i].meta['closable'] = findRes.meta.closable
				routes.push(findRes)
			}
			if (asideMenus[i].children.length > 0) {
				handle(asideMenus[i].children, permissionRoutes)
			}
		}
	})(asideMenus, permissionRoutes)
	return routes
}

// 菜单数据
let asideMenus = store.state.app.asideMenus
if (asideMenus.length <= 0) {
	
}
const haveRoutes = handleMenus(asideMenus, permissionRoutes)
haveRoutes.forEach(item => router.addRoute('main', item))

EventCenter.addEvent('login', (menus, permissions, userInfo) => {
	const haveRoutes = handleMenus(menus, permissionRoutes)
	haveRoutes.forEach(item => router.addRoute('main', item))
	
	store.commit('app/setAsideMenus', menus)
	store.commit('app/setPermissions', permissions)
	store.commit('app/setHaveRoutes', haveRoutes)
	store.commit('user/setUserInfo', userInfo)
})

// 全局路由前置守卫
router.beforeEach((to, from) => {
	NProgress.start()
	const userInfo = store.state.user.userInfo
	const lockStatus = store.state.user.lockStatus
	if (to.name !== 'login' && to.name !== 'lock' && lockStatus == 1) {
		return {
			path: '/lock'
		}
	}
	if (to.name !== 'login' && !userInfo) {
		return {
			path: '/login'
		}
	}
	if (to.name == 'login' && userInfo) {
		return {
			path: '/main'
		}
	}
})
// 全局路由后置守卫
router.afterEach((to, from) => {
	NProgress.done()
})

export default router